package com.monkeybrother.thread.pool;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ScheduledThreadPoolExecutorTest {
    static ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(1);
    public static void main(String[] args) throws InterruptedException {
//
        new Thread(() ->{
            CountDownLatch countDownLatch1 = new CountDownLatch(1);
            // 创建固定时延的定时任务
            ScheduledFuture<?> scheduledFuture1 = pool.scheduleWithFixedDelay(
                    new Task2(countDownLatch1, 10)
                    , 0
                    , 1, TimeUnit.SECONDS);

            try {
                countDownLatch1.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            // 同步计数器已归零，说明定时任务已满足条件退出
            // 所以取消定时任务
            scheduledFuture1.cancel(true);
        }).start();


       new Thread(() ->{
           CountDownLatch countDownLatch2 = new CountDownLatch(1);
           // 创建固定时延的定时任务
           ScheduledFuture<?> scheduledFuture2 = pool.scheduleWithFixedDelay(
                   new Task2(countDownLatch2, 20)
                   , 0
                   , 1, TimeUnit.SECONDS);

           try {
               countDownLatch2.await();
           } catch (InterruptedException e) {
               throw new RuntimeException(e);
           }
           // 同步计数器已归零，说明定时任务已满足条件退出
           // 所以取消定时任务
           scheduledFuture2.cancel(true);
       }).start();


        // 关闭线程池
        // pool.shutdown();
    }

}

class Task2 implements Runnable {

    CountDownLatch countDownLatch;
    private int counter;

    public Task2(CountDownLatch countDownLatch, int counter) {
        this.countDownLatch = countDownLatch;
        this.counter = counter;
    }

    @Override
    public void run() {
        LocalDateTime localDateTime = LocalDateTime.now();
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 处理一些任务
        System.out.println(localDateTime.format(dtf) + " [" + Thread.currentThread().getName() + "] " + counter);

        if (counter-- == 0) {
            // 判断达到停止任务的条件
            countDownLatch.countDown();
        }
    }
}